<?php
/**
 * 工具管理
 * Created by PhpStorm.
 * User: dell
 * Date: 2018/6/29
 * Time: 18:09
 */
namespace app\admin\controller;
use app\admin\model\Admin;
use app\repository\Repository;
use think\Db;
use think\Request;
use think\Validate;
use clt\Leftnav;
class Tools extends Common
{
    /**
     * 列表页面
     * @return mixed
     */
    public function listUI(){
        return $this->fetch('list');
    }

    /**
     * 类型页面
     * @return mixed
     */
    public function cateUI(){
        return $this->fetch('cate');
    }

    /**
     * 添加页面
     * @return mixed
     */
    public function addUI(){
        $this->assign('info','null');
        return $this->fetch('add');
    }

    /**
     * 修改页面
     * @return mixed
     */
    public function editUI(){

        $info = db('tools')->where('id',input('id'))->find();
        $this->assign('info',json_encode($info));
        return $this->fetch('add');
    }

    /**
     * 工具管理员
     * @return mixed
     */
    public function adminUI(){
        return $this->fetch('admin');
    }

/****************工具管理员********************/
    /**
     * 分配权限
     * @return mixed
     */
    public function accessUI(){

        $nav = new Leftnav();
        $admin_rule=db('auth_rule')->field('id,pid,title')->order('sort asc')->select();

        $data = Repository::treeData($admin_rule);
        $ac = [];
        foreach ($data as $v){
            if($v['id'] == 294){
                $ac = $v;
            }
        }
        $data = [];
        $data[] = [
            'id'=>$ac['id'],
            'pid'=>$ac['pid'],
            'title'=>$ac['title']
        ];
        if(count($ac['children'])>0){
            foreach ($ac['children'] as $v1){
                if($v1['id'] != 296)
                $data[] = [
                    'id'=>$v1['id'],
                    'pid'=>$v1['pid'],
                    'title'=>$v1['title']
                ];
                if(count($v1['children'])>0){
                    foreach ($v1['children'] as $v2){
                        $data[] = [
                            'id'=>$v2['id'],
                            'pid'=>$v2['pid'],
                            'title'=>$v2['title']
                        ];
                    }
                }
            }
        }
        $rules = db('admin')->where('admin_id',input('id'))->value('rules');
        $arr = $nav->auth($data,$pid=0,$rules);

        $arr[] = array(
            "id"=>0,
            "pid"=>0,
            "title"=>"全部",
            "open"=>true
        );
        $this->assign('data',json_encode($arr,true));
        return $this->fetch('admin_access');
    }

    /**
     * 保存权限
     * @param Request $request
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function groupSetaccess(Request $request){
        $rul = $request->param('rules');
        $aid = $request->param('admin_id');

        if(empty($aid)) return ['code'=>0,'msg'=>'admin_id参数错误'];
        if(empty($rul)) return ['code'=>0,'msg'=>'请选择权限'];

        $row = db('admin')->where('admin_id',$aid)->update(['rules'=>$rul]);

        if($row)
            return ['code'=>1,'msg'=>'提交成功'];
        return ['code'=>0,'msg'=>'提交失败'];

    }

    /**
     *  工具管理员列表
     * @param Request $request
     * @return array
     */
    public function queryAdmin(Request $request){
        $input = $request->param();
        if(empty($input['gid'])) return ['code'=>1,'msg'=>'gid参数错误'];
        $rows = db('admin')->alias('a')->where(function ($query)use($input){
            if(!empty($input['gid']))
                $query->where('a.group_id',$input['gid']);
            if(!empty($input['is_part']))
                $query->where('a.is_part',$input['is_part']);
            if(!empty($input['aid']))
                $query->where('a.admin_id',$input['aid']);
            if(!empty($input['apid']))
                $query->where('a.a_pid',$input['apid']);
        })
            ->join('auth_group ag','a.group_id=ag.group_id','left')
            ->join('jobs js','js.id=a.jobs_id','left')
            ->join('admin as','a.a_pid=as.admin_id','left')
            ->field(['a.*,ag.title','js.title as jobs_title','as.username as as_username','as.name as as_name'])
            ->select();
        return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$rows,'rel'=>1];
    }

    /**
     * 工具管理添加
     * @return mixed
     */
    public function adminAddUI(Request $request){
        if($request->isPost()){
            $data = input('post.');

            $check_user = Admin::get(['username'=>$data['username']]);
            if ($check_user) {
                return $result = ['code'=>0,'msg'=>'用户已存在，请重新输入用户名!'];
            }
            $data['pwd'] = input('post.pwd', '', 'md5');
            $data['add_time'] = time();
            $data['ip'] = request()->ip();
            $data['group_id'] = 8;
            $data['a_pid'] = session('aid');

            //验证
            $msg = $this->validate($data,'app\admin\validate\Admin');
            if($msg!='true'){
                return json(['code'=>0,'msg'=>$msg]);
            }
            //单独验证密码
            $checkPwd = Validate::make([input('post.pwd')=>'require']);
            if (false === $checkPwd) {
                return json(['code'=>0,'msg'=>'密码不能为空！']);
            }
            //添加
            if (Admin::create($data)) {
                return json(['code'=>1,'msg'=>'添加成功!','url'=>url('adminUI')]);
            } else {
                return json(['code'=>0,'msg'=>'添加失败!']);
            }
        }else{
            $row = db('admin')->where('group_id',6)->field(['admin_id,username,name'])->select();
            $this->assign('info','null');
            $this->assign('des',1);
            return $this->fetch('adminAdd',['sel'=>$row]);
        }

    }

    /**
     * 工具管理员编辑
     * @param Request $request
     * @return array|mixed|\think\response\Json
     * @throws \think\exception\DbException
     */
    public function adminEditUI(Request $request){
        if($request->isPost()){
            $data = input('post.');
            $pwd=input('post.pwd');
            $map[] = ['admin_id','<>',$data['admin_id']];
            $where['admin_id'] = $data['admin_id'];

            if($data['username']){
                $map[] = ['username','=',$data['username']];
                $check_user = Admin::where($map)->find();
                if ($check_user) {
                    return $result = ['code'=>0,'msg'=>'用户已存在，请重新输入用户名!'];
                }
            }
            if ($pwd){
                $data['pwd']=input('post.pwd','','md5');
            }else{
                unset($data['pwd']);
            }
            $msg = $this->validate($data,'app\admin\validate\Admin');
            if($msg!='true'){
                return $result = ['code'=>0,'msg'=>$msg];
            }
            Admin::update($data,$where);
            //session('username',$data['username']);
            $avatar = $data['avatar']==''?'/public/static/admin/images/0.jpg':$data['avatar'];
            //session('avatar',$avatar);
            return $result = ['code'=>1,'msg'=>'管理员修改成功!','url'=>url('adminUI')];
        }else{
            $row = db('admin')->where('group_id',6)->field(['admin_id,username,name'])->select();
            $admin = new Admin();
            $info = $admin->getInfo(input('admin_id'));
            $this->assign('info', json_encode($info,JSON_UNESCAPED_UNICODE));
            $this->assign('title',lang('edit').lang('admin'));
            $this->assign('des',0);
            return $this->fetch('adminAdd',['sel'=>$row]);
        }
    }

    //修改管理员状态
    public function adminState(){
        $id=input('post.id');
        $is_open=input('post.is_open');
        if (empty($id)){
            $result['status'] = 0;
            $result['info'] = '用户ID不存在!';
            $result['url'] = url('adminList');
            return $result;
        }
        db('admin')->where('admin_id='.$id)->update(['is_open'=>$is_open]);
        $result['status'] = 1;
        $result['info'] = '用户状态修改成功!';
        $result['url'] = url('adminUI');
        return $result;
    }
    
/****************工具管理员*结束*******************/

    /**
     * 工具列表
     * @param Request $request
     * @return array
     */
    public function queryPage(Request $request){
        $input = $request->param();

        if(session('gid')==8){
            $row = db('admin')->where('admin_id',session('aid'))->find();
            $input['admin_id'] = $row['a_pid'];
        }else if(session('gid')==6){
            $input['admin_id'] = session('aid');
        }

        $rows = db('tools')->alias('t')
            ->where(function ($query)use($input){
                if(!empty($input['number']))
                    $query->where('t.number',$input['number']);
                if(!empty($input['state_id']))
                    $query->where('t.state_id',$input['state_id']);
                if(!empty($input['type_id']))
                    $query->where('t.type_id',$input['type_id']);
                if(!empty($input['key']))
                    $query->where('t.number|t.title',$input['key']);
                if(!empty($input['admin_id']))
                    $query->where('t.admin_id',$input['admin_id']);


            })
            ->join('tools_type tt','tt.id=t.type_id','left')
            ->join('state s','s.id=t.state_id','left')
            ->field(['t.*','tt.type_name','s.state_name'])
            ->paginate($input['limit'])
            ->toArray();

        $data = [];
        foreach ($rows['data'] as $v){

            if($v['check_date'])
            $v['sur_waring'] = $v['waring']-ceil((((time()-strtotime($v['check_date']))/60)/60)/24);

            $data[] = $v;
        }

        return ['code'=>0,'msg'=>'获取成功!','data'=>$data,'count'=>$rows['total'],'rel'=>1];
    }

    /**
     * 添加工具
     * @param Request $request
     * @return array
     */
    public function add(Request $request){
        $input = $request->param();
        if(session('gid') != 8) return ['code'=>0,'msg'=>'请使用工具管理员账号操作'];
        if(empty($input['title'])) return ['code'=>0,'msg'=>'名称不能为空'];
        $input['state_id'] = 30;

        $row = db('admin')->where('admin_id',session('aid'))->find();

        $input['admin_id'] = $row['a_pid'];

        $num_arr = explode(',',$input['number']);

        $det = [];
        foreach ($num_arr as $v){
            $input['number'] = $v;
            $det[] = $input;
        }

        $row = db('tools')->insertAll($det);

        if($row)
            return ['code'=>1,'msg'=>'添加成功'];
        return ['code'=>0,'msg'=>'添加失败'];
    }

    /**
     * 修改工具信息
     * @param Request $request
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function edit(Request $request){
        $input = $request->param();

        if(session('gid') != 8) return ['code'=>0,'msg'=>'请使用工具管理员账号操作'];
        if(empty($input['id'])) return ['code'=>0,'msg'=>'id参数错误'];
        if(empty($input['title'])) return ['code'=>0,'msg'=>'名称不能为空'];

        $row = db('tools')->where('id',$input['id'])->update($input);

        if($row)
            return ['code'=>1,'msg'=>'修改成功'];
        return ['code'=>0,'msg'=>'修改失败'];
    }

    /**
     * 删除工具
     * @param Request $request
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function del(Request $request){
        $tid = $request->param('id');
        if(empty($tid)) return ['code'=>0,'msg'=>'id参数错误'];

        $row = db('tools')->where('id',$tid)->delete();

        if($row)
            return ['code'=>1,'msg'=>'删除成功'];
        return ['code'=>0,'msg'=>'删除失败'];

    }

    /**
     * 去校验工具ids
     * @param Request $request
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function toCheck(Request $request){
        $ids = $request->param('ids');
        $arr = explode(',',$ids);
        $row = db('tools')->where('id','in',$arr)->update(['state_id'=>45]);
        if($row)
            return ['code'=>1,'msg'=>'操作成功'];
        return ['code'=>0,'msg'=>'操作失败'];
    }

    /**
     * 校验完成 ids dat
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function compCheck(Request $request){
        $ids = $request->param('ids');
        $arr = explode(',',$ids);
        $date = $request->param('dat');
        if(empty($date)) $date = date('Y-m-d',time());
        $row = db('tools')->where('id','in',$arr)->update(['state_id'=>30,'check_date'=>$date]);
        if($row)
            return ['code'=>1,'msg'=>'操作成功'];
        return ['code'=>0,'msg'=>'操作失败'];
    }

    /**
     * 检测工具,无效
     * @throws \think\exception\DbException
     */
    public function checkTools(){
        $det = [];
        db('tools')->where('is_check',1)->chunk(100,function ($query){
            foreach ($query as $v){
                $tem = [
                    'id'=>$v['id'],
                    'over'=>$v['waring']-ceil((((time()-strtotime($v['check_date']))/60)/60)/24),
                ];
                if($tem['over']&&$tem['over']<=0){
                    $tem['state_id'] = 44;
                    $det[] = $tem;
                }
            }
        });


        $tools = new \app\admin\model\Tools();

        $row = $tools->isUpdate()->saveAll($det);

        return ['code'=>1,'msg'=>'','d'=>$row];
    }


    /**
     * 使用记录
     * @param Request $request
     * @return array
     */
    public function lendRec(Request $request)
    {
        $input = $request->param();
        $rows = db('tools_lend_record')
            ->alias('tr')
            ->order('tr.id desc')
            ->where('tr.tools_id',$input['id'])
            ->join('tools_lend tl','tl.id=tr.lend_id','left')
            ->join('state s','s.id=tr.state_id','left')
            ->field(['tr.*','tl.out_name','tl.input_name','tl.lend_time','s.state_name'])
            ->paginate($input['per_page']);
        return ['code'=>1,'msg'=>'获取成功','data'=>$rows];
    }

    /********************类型操作******************/

    /**
     * 类型列表
     * @return array|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function typeList(){

        return $rows = db('tools_type')->order('sort asc')->select();

    }

    /**
     * 类型添加
     * @param Request $request
     * @return array
     */
    public function typeAdd(Request $request)
    {
        $input = [
            'type_name'=>$request->param('type_name'),
            'sort'=>$request->param('sort')
        ];
        $row = db('tools_type')->insertGetId($input);
        if($row)
            return ['code'=>1,'msg'=>'添加成功'];
        return ['code'=>0,'msg'=>'添加失败'];
    }

    /**
     * 类型修改
     * @param Request $request
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function typeEdit(Request $request)
    {
        $input = $request->param();
        if(empty($input['id'])) return ['code'=>0,'msg'=>'id参数错误'];
        $row = db('tools_type')->where('id',$input['id'])->update($input);
        if($row)
            return ['code'=>1,'msg'=>'修改成功'];
        return ['code'=>0,'msg'=>'修改失败'];
    }

    /**
     * 类型删除
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function typeDel(Request $request){
        $input = $request->param();
        if(empty($input['id'])) return ['code'=>0,'msg'=>'id参数错误'];
        $row = db('tools_type')->where('id',$input['id'])->delete();
        if($row)
            return ['code'=>1,'msg'=>'删除成功'];
        return ['code'=>0,'msg'=>'删除失败'];
    }
}